package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.SignIn;
import cn.wolfcode.trip.base.mapper.SignInMapper;
import cn.wolfcode.trip.base.service.ISignInService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

@Service
public class SignInServiceImpl implements ISignInService {
    @Autowired
    private SignInMapper signInMapper;

    //未签到的情况下,执行该语句
    @Override
    public void saveOrUpdate(Long id) throws ParseException {
        //根据用户id查询数据库签到对象

        SignIn signIn = signInMapper.selectByPrimaryKey(id);
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String strToday = sdf.format(date);
        Date today = sdf.parse(strToday);
        //创建日历对象
        Calendar c = Calendar.getInstance();
        //获取前一天日期
        c.add(Calendar.DAY_OF_MONTH, -1);
        //获取昨天日期字符串
        String strYesterday = sdf.format(c.getTime());
        //如果对象为空,首次为首次签到
        if (signIn == null) {
            signIn = new SignIn(id, today, 1, 100, 1);
            signInMapper.insert(signIn);
            return;
        }
        //如果对象不为空
        if (signIn != null) {
            Date date1 = signIn.getDate();
            Integer condays = signIn.getCondays();
            String strDate = sdf.format(date1);
            //且数据库日期是昨天的&&连续签到天数大于等于6   说明今天是第7天以上
            if (strDate.equals(strYesterday) && condays >= 6) {
                signIn.setDate(today);
                signIn.setCondays(condays + 1);
                signIn.setIntegral(signIn.getIntegral() + 200);
                signIn.setTotalDays(signIn.getTotalDays() + 1);
                signInMapper.updateByPrimaryKey(signIn);

                //或者  数据库日期是昨天的&&连续签到天数小于6
            } else if (strDate.equals(strYesterday) && condays < 6) {
                signIn.setDate(today);
                signIn.setCondays(condays + 1);
                signIn.setIntegral(signIn.getIntegral() + 100);
                signIn.setTotalDays(signIn.getTotalDays() + 1);
                signInMapper.updateByPrimaryKey(signIn);

                // 数据库日期不等于昨天的,说明断签
            } else if (!strDate.equals(strYesterday)) {
                signIn.setDate(today);
                signIn.setCondays(1);
                signIn.setIntegral(signIn.getIntegral() + 100);
                signIn.setTotalDays(signIn.getTotalDays() + 1);
                signInMapper.updateByPrimaryKey(signIn);

            }

        }

    }

    @Override//今日已签到判断    只需要通过判断控制按钮的状态
    public SignIn getByIdAndDate(Long id, Date date) {
        //通过id和今天日期能否查到对象
        SignIn signIn = signInMapper.selectByIdAndDate(id, date);

        return signIn;
    }
    //根据id查询对象,用于签到后的对象返回
    @Override
    public SignIn getById(Long id) {
        return signInMapper.selectByPrimaryKey(id);
    }
}
